package com.cl.short_video_java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.short_video_java.common.Const;
import com.cl.short_video_java.mapper.SysMenuMapper;
import com.cl.short_video_java.pojo.SysMenu;
import com.cl.short_video_java.pojo.SysRoleMenu;
import com.cl.short_video_java.pojo.VideoRole;
import com.cl.short_video_java.pojo.VideoUser;
import com.cl.short_video_java.service.SysMenuService;
import com.cl.short_video_java.service.SysRoleMenuService;
import com.cl.short_video_java.service.VideoRoleService;
import com.cl.short_video_java.mapper.VideoRoleMapper;
import com.cl.short_video_java.service.VideoUserService;
import com.cl.short_video_java.util.StringUtils;
import com.cl.short_video_java.vo.role.Role;
import com.cl.short_video_java.vo.role.RoleSearch;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author object
 * @description 针对表【video_role(角色信息表)】的数据库操作Service实现
 * @createDate 2024-10-31 15:58:59
 */
@Service
public class VideoRoleServiceImpl extends ServiceImpl<VideoRoleMapper, VideoRole>
		implements VideoRoleService {


	private VideoRoleMapper videoRoleMapper;
	private VideoUserService videoUserService;
	private SysRoleMenuService sysRoleMenuService;
	private SysMenuMapper sysMenuMapper;

	VideoRoleServiceImpl(VideoRoleMapper videoRoleMapper,
						 VideoUserService videoUserService,
						 SysRoleMenuService sysRoleMenuService,
						 SysMenuMapper sysMenuMapper) {
		this.videoRoleMapper = videoRoleMapper;
		this.videoUserService = videoUserService;
		this.sysRoleMenuService = sysRoleMenuService;
		this.sysMenuMapper = sysMenuMapper;
	}

	/**
	 * 批量删除角色
	 *
	 * @param idlist
	 * @return
	 */
	@Override
	public Boolean DeleteService(String idlist) {
		String[] ids = idlist.split(",");
		return this.removeBatchByIds(Arrays.asList(ids));
	}

	/**
	 * 根据搜索条件获取角色信息（查询列表）
	 *
	 * @param roleSearch
	 * @return
	 */
	@Override
	public List<VideoRole> search(RoleSearch roleSearch) {
		List<VideoRole> list = this.list(new QueryWrapper<VideoRole>()
				.like(!StringUtils.isEmpty(roleSearch.getRoleName()), "role_name", roleSearch.getRoleName())
				.like(!StringUtils.isEmpty(roleSearch.getRoleKey()), "role_key", roleSearch.getRoleKey())
				.eq(roleSearch.getStatus() != null, "status", roleSearch.getStatus())
				.orderByAsc("role_sort")
		);
		for (VideoRole videoRole : list) {
			if ("admin".equals(videoRole.getRoleKey())) {
//				超管
				List<SysMenu> list1 = sysMenuMapper.selectList(new QueryWrapper<SysMenu>());
				List<Long> menuIds = list1.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
				videoRole.setSysMenuList(menuIds);
			} else {
				List<SysRoleMenu> id = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>()
						.eq("role_id", videoRole.getRoleId())
						.eq("status", 1));
				List<Long> collect = id.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
				videoRole.setSysMenuList(collect);
			}
		}
		return list;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Role role, HttpServletRequest request) {
		VideoUser user = videoUserService.getCurrentUser(request, Const.GRADE_ADMIN);
		if (role.getId() != null) {
			// 修改
			update(role, user.getUsername());
		} else {
			insert(role, user.getUsername());
		}
	}

	@Override
	public void del(List<Integer> ids) {
		this.removeBatchByIds(ids);
		sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));
	}

	/**
	 * 设置用户角色
	 *
	 * @param id
	 * @param roleId
	 */
	@Override
	public void setUser(Integer id, Integer roleId) {
		videoUserService.update(new UpdateWrapper<VideoUser>()
				.eq("id", id)
				.set("role_id", roleId)
				.set("is_admin", 1)
		);
	}

	@Override
	public void cancel(Integer id) {
		videoUserService.update(new UpdateWrapper<VideoUser>().eq("id", id).set("is_admin", 0).set("role_id", null));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void limit(Integer rid) {
		VideoRole role = this.getOne(new QueryWrapper<VideoRole>().eq("role_id", rid));
		role.setStatus(role.getStatus() == 1 ? 0 : 1);
		this.updateById(role);
	}

	private void insert(Role role, String username) {
		long count = this.count(new QueryWrapper<VideoRole>().eq("role_key", role.getRoleKey()));
		System.out.println(count);
		Assert.isTrue(count == 0, "当前字符已存在");
		// 新增、
		VideoRole videoRole = new VideoRole();
		videoRole.setRoleSort(2);
		videoRole.setRoleKey(role.getRoleKey());
		videoRole.setRoleName(role.getRoleName());
		videoRole.setUpdateTime(LocalDateTime.now());
		videoRole.setUpdateBy(username);
		videoRole.setRemark("普通管理员");
		videoRole.setStatus(role.getStatus());
		this.save(videoRole);
		VideoRole roleKey = this.getOne(new QueryWrapper<VideoRole>().eq("role_key", role.getRoleKey()));
		List<SysMenu> list = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().select("menu_id", "order_num"));
		List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
		for (SysMenu sysMenu : list) {
			SysRoleMenu sysRoleMenu = new SysRoleMenu();
			sysRoleMenu.setRoleId(roleKey.getRoleId());
			sysRoleMenu.setMenuId(sysMenu.getMenuId());
			sysRoleMenu.setStatus(role.getSysMenuList().indexOf(sysMenu.getMenuId()) == -1 ? 0 : 1);
			sysRoleMenu.setOrderNum(sysMenu.getOrderNum());
			sysRoleMenus.add(sysRoleMenu);
		}
		sysRoleMenuService.saveBatch(sysRoleMenus);
	}


	private void update(Role role, String username) {
		// 修改
		VideoRole videoRole = new VideoRole();
		videoRole.setRoleId(Long.valueOf(role.getId()));
		videoRole.setRoleSort(2);
		videoRole.setRoleKey(role.getRoleKey());
		videoRole.setRoleName(role.getRoleName());
		videoRole.setUpdateTime(LocalDateTime.now());
		videoRole.setUpdateBy(username);
		this.saveOrUpdate(videoRole, new UpdateWrapper<VideoRole>().eq("role_id", videoRole.getRoleId()));

		sysRoleMenuService.save(role.getId(), role.getSysMenuList());
	}
}




